<script setup>
import {ref, reactive, onMounted, computed, getCurrentInstance,toRaw} from 'vue';
import {useRouter} from "vue-router";
import {getLocalStorage, getSessionStorage, removeLocalStorage} from "../main.js";
import axios from "axios";  // Import defineProps from Vue
import qs from 'qs';

let internalInstance = getCurrentInstance();

let message=internalInstance.appContext.config.globalProperties.$message
const foodList = ref([]);
const businessId=ref();
let business=reactive({});
const router = useRouter();
let orderedList=ref([])
let user=ref({})
let deliveryaddress=ref({})
let detailetList=ref([])
let cartList=ref([])

const totalPrice  = computed(() => {
  let totalPrice = 0;
  for(let cartItem of cartList.value){
    totalPrice += cartItem.food.foodPrice*cartItem.quantity;
  }
  totalPrice += business.deliveryPrice;
  return totalPrice;
});

onMounted(() => {
  businessId.value=router.currentRoute.value.query.businessId
  console.log(businessId.value)
  user.value=getSessionStorage('user')
  // console.log(user.value.userId)
  // console.log(router.currentRoute.value.query)
  // foodList.value =JSON.parse(router.currentRoute.value.query.foodList)
  // foodList.value.forEach(item => {
  //   if (item.quantity !== 0) {
  //     orderedList.value.push(item)
  //   }
  // });

  // orderedList.value =JSON.parse(router.currentRoute.value.query.orderedList)
  // orderedList.value.forEach(item => {
  //   if (item.quantity !== 0) {
  //     detailetList.value = [...detailetList.value, {
  //       foodId: item.foodId,
  //       quantity: item.quantity
  //     }];
  //   }
  // });
  loadBusiness();
//查询当前用户在购物车中的当前商家食品列表
  axios.post('cart/listCart',{
      userId:user.value.userId,
      businessId:businessId.value
  }).then(response=>{
    cartList.value = response.data;
    // console.log(cartList.value)
  }).catch(error=>{
    console.error(error);
  });


  deliveryaddress.value=getLocalStorage(user.value.userId)

  // console.log(businessId)


  // console.log(business)




  // totalOrderPrice.value=computedTotalOrderPrice.value

  // console.log(computedTotalOrderPrice.value);
});

async function loadBusiness() {
  // console.log(businessId)
  try {
    // console.log(businessId)
    const response = await axios.get("/business/getBusinessById", {
      params: { businessId: businessId.value },
    });
    Object.assign(business, response.data);
  } catch (error) {
    console.error(error);
  }
}

// function gotoUserAddress(){
//   router.push({ path: "/userAddress",query:{businessId:businessId.value,foodList:JSON.stringify(foodList.value)}});
// }
function gotoUserAddress(){
  router.push({ path: "/userAddress",query:{businessId:businessId.value}});
}

function backToBusinessInfo() {
  router.push({ path: "/businessInfo" ,query:{businessId:businessId.value}});
}

function sexFilter(num){
  if (num==null)return
  else{
    return num==1?"先生":"女士"
  }

}

function gotoPayment(){
  if(deliveryaddress==null){
    message.error('请选择送货地址！');
    return;
  }
  // console.log(deliveryaddress.value.daId)

  // 创建订单
  axios({
    method:"POST",
    url:"/orders/createOrders",
    data:{
      userId:user.value.userId,
      businessId:businessId.value,
      orderState:0,
      daId:deliveryaddress.value.daId,
      orderTotal:totalPrice.value,
      list:detailetList.value
    }
  }).then(response=>{
    console.log(response)
    let orderId = response.data;
    if(orderId>0){
      removeLocalStorage(businessId.value)
      for (const item of orderedList.value) {
        removeLocalStorage(item.foodId)
        // 在这里执行你想要的操作
      }
      router.push({path:'/payment',query:{orderId:orderId}});
    }else{
      alert('创建订单失败！');
    }
  }).catch(error=>{
    console.error(error);
  });
}


</script>

<template>
  <div class="wrapper">
    <!--    header部分-->
    <header>
      <p class="back" @click="backToBusinessInfo">&lt; 返回</p>
      <p>确认订单</p>
    </header>
    <!--    订单信息部分-->
    <div class="order-info" @click="gotoUserAddress">
      <h5>订单配送至：</h5>
      <div class="order-info-address">
        <p>{{deliveryaddress!=null?deliveryaddress.address:'请选择送货地址'}}</p>
        <p>></p>
      </div>
      <p >{{deliveryaddress?.contactName}}{{sexFilter(deliveryaddress?.contactSex)}} {{deliveryaddress?.contactTel}}</p>
    </div>
    <h3>{{business.businessName}}</h3>
    <!--订单明细部分-->
    <ul class="order-detail">
      <li v-for="(item,i) in cartList" :key="i">
                <div class="order-detail-left" v-if="item.quantity!=0">
                  <img :src="item.food.foodImg">
                  <p>{{item.food.foodName}} x {{item.food.quantity}}</p>
                </div>
                <p>&#165;{{item.food.foodPrice*item.quantity}}</p>

      </li>
        <div class="order-deliveryfee">
          <p>配送费</p>
          <p>&#165;{{business.deliveryPrice}}</p>
        </div>



    </ul>
    <!--      底部合计部分-->
    <div class="total">
      <div class="total-left">
        &#165;{{totalPrice!=NaN?totalPrice:0}}
      </div>
      <div class="total-right" @click="gotoPayment">
        去支付

      </div>
    </div>

  </div>
</template>

<style scoped>
/*总容器*/
.wrapper{
  width: 100%;
  height: 100%;
}
/*header部分*/
.wrapper header{
  width:100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;

}
.wrapper header .back{
  position: absolute;
  left:7px;
  display: flex;
  align-items: center;
  text-align: center;
}
/*订单信息部分*/
.wrapper .order-info{
  width: 100%;
  margin-top: 12vw;
  background-color: #0097FF;
  box-sizing: border-box;
  padding: 2vw;
  color: #fff;
}
.wrapper .order-info h5{
  font-size: 3vw;
  font-weight: 300;
}
.wrapper .order-info .order-info-address{
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  margin: 1vw 0;
}
.wrapper .order-info .order-info-address p{
  //width: 90%;
  font-size: 5vw;
}


.wrapper .order-info .order-info-address i{
  font-size: 6vw;
}
.wrapper .order-info p{
  font-size: 3vw;

}
.wrapper h3{
  box-sizing: border-box;
  padding: 3vw;
  font-size: 4vw;
  color: #666;
  border-bottom: solid 1px #DDD;
}
/*订单明细部分*/
.wrapper .order-detail{
  width: 100%;
}
.wrapper .order-detail li{
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;

  display: flex;
  justify-content: space-between;
  align-items: center;

}
.wrapper .order-detail li .order-detail-left{
  display: flex;
  align-items: center;
}
.wrapper .order-detail li .order-detail-left img{
  width: 10vw;
  height: 10vw;

}
.wrapper .order-detail li .order-detail-left p{
  font-size: 3.5vw;
  margin-left: 3vw;

}
.wrapper .order-detail li p{
  font-size: 3.5vw;

}
.wrapper .order-deliveryfee{
  width: 100%;
  height: 16vw;
  box-sizing: border-box;
  padding: 3vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 3.5vw;
}
/*底部合计部分*/
.wrapper .total{
  width: 100%;
  height: 14vw;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;

}
.wrapper .total .total-left{
  flex: 2;
  background-color: #505051;
  color: white;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  display: flex;
  justify-content: center;
  align-items: center;

}
.wrapper .total .total-right{
  flex: 1;
  background-color: #38CA73;
  color: white;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

}

</style>